package com.weishuang.monitor.leader.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.Page;
import com.weishuang.monitor.leader.commons.entity.Result;
import com.weishuang.monitor.leader.commons.enums.SCODE;
import com.weishuang.monitor.leader.commons.utils.ResultUtils;
import com.weishuang.monitor.leader.commons.utils.UserUtils;
import com.weishuang.monitor.leader.entity.SysUser;
import com.weishuang.monitor.leader.entity.dto.UserDTO;
import com.weishuang.monitor.leader.service.ISysUserService;
import com.weishuang.monitor.leader.service.SysCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author weishuang
 * @since 2021-03-23
 */
@RestController
@RequestMapping("/leader/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysCacheService sysCacheService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping
    public Result addUser(@Validated SysUser sysUser) {
        sysUser.setId(IdWorker.getIdStr());
        sysUser.insertInit();
        sysUser.setPassword(passwordEncoder.encode(SCODE.DEFUALT_PASSWORD.getValue()));
        sysUserService.save(sysUser);
        return ResultUtils.success();
    }

    @PutMapping("/{id}")
    public Result updateUser(@PathVariable String id, @Validated SysUser sysUser) {
        sysUser.setId(id);
        sysUser.updateInit();
        sysUserService.updateById(sysUser);
        sysCacheService.clearSysUserByUserId(id);
        return ResultUtils.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable String id) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(SysUser::getId, id);
        updateWrapper.eq(SysUser::getIsDefault, SCODE.NO_CODE.getValue());
        SysUser sysUser = new SysUser();
        sysUser.deleteInit();
        sysUserService.update(sysUser, updateWrapper);
        sysCacheService.clearSysUser(id);
        return ResultUtils.success();
    }

    @GetMapping("/{id}")
    public Result getUserById(@PathVariable String id) {
        SysUser byId = sysUserService.getById(id);
        return ResultUtils.success(byId);
    }

    @GetMapping("/page")
    public Result getUserPage(UserDTO user) {
      Page<SysUser> page = sysUserService.getUserPage(user);
        return ResultUtils.success(page);
    }

    @GetMapping("/getCurrentUserInfo")
    public Result getCurrentUserInfo() {
        String userId = UserUtils.getUserId();
        SysUser byId = sysUserService.getById(userId);
        return ResultUtils.success(byId);
    }
}
